'''
Created on 14/04/2009

@author: eh01
'''
from im.ds import dsconstants, dsofactory
from im.ds.dsstub import DSStub
from im.event import eventconstants
from im.event.event import Event
from im.event.eventhandler import BaseEventHandler
from im.event.eventmanager import EventManager
from im.logindecorator import adminLoginRequired
import httplib
import os

class HTTPRequestPOSTFlushMemcacheHandler(BaseEventHandler):

    @adminLoginRequired
    def do(self, data):
        dso = data
        ds_stub = DSStub()
        http_request = dso.get_dst(subject=dsconstants.SUBJECT_ROOT,
                    predicate=dsconstants.PREDICATE_HTTP_REQUEST).get_literal()
        lock = dso.get_dst(subject=dsconstants.SUBJECT_ROOT,
                    predicate=dsconstants.PREDICATE_LOCK).get_literal()                    
        event_type = eventconstants.HTTP_RESPONSE_EVENT_TYPE
        # get the path of the appropriate html template
        relative_path = "../../../pages/hub/flush-memcache-confirmation.html"
        
        # get the html
        template_path = os.path.join(os.path.dirname(__file__), relative_path)
        file = open(template_path)
        html_template_string = file.read()
        items_flushed = ds_stub.flush_memcache()            
        html_string = html_template_string.replace('${number_of_items_flushed}', str(items_flushed))
        # create new dso        
        new_dso = dsofactory.create_dso_for_im_http_response_handler(httplib.OK, 
                                                               'text/html', 
                                                               html_string, 
                                                               http_request, 
                                                               lock)            
        event = Event(event_type, new_dso)
        EventManager().add_event(event)        